package com.gitee.apanlh.util.valid;

import com.gitee.apanlh.annotation.valid.ValidConstant;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.base.StringUtils;
import com.gitee.apanlh.util.log.Log;
import com.gitee.apanlh.util.reflection.ClassUtils;
import com.gitee.apanlh.util.reflection.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;


/**
 * 	校验常量是否有效
 * 	
 * 	@author Pan
 */
public class ValidClassConstant {
	
	/**
	 * 	构造函数
	 * 
	 * 	@author Pan
	 */
	private ValidClassConstant() {
		//	不允许外部实例
		super();
	}
	
	/**	
	 * 	验证某个包下静态常量是否有效
	 * 	<br>传递包路径即可
	 * 
	 * 	@author Pan
	 * 	@param 	packagePath		包路径
	 */
	public static void valid(String packagePath) {
		//	 获取包
		List<Class<?>> currentPackageAllClass = ClassUtils.getPackageClasses(packagePath);
		Assert.isNotNull(currentPackageAllClass, StringUtils.format("scanner package error, please check package path:{}", packagePath));
		
		//	验证有效常量
		for (int i = 0; i < currentPackageAllClass.size(); i++) {
			Class<?> clazz = currentPackageAllClass.get(i);
			if (ReflectionUtils.getClassAnnotation(clazz, ValidConstant.class) != null) {

				Object bean = ReflectionUtils.newInstance(clazz);
				Map<String, Field> fieldsToMap = ReflectionUtils.getFieldsToMap(clazz);

				IteratorUtils.entrySet(fieldsToMap, (k, v) -> {
					if (!ReflectionUtils.isStaticField(v)) {
						return ;
					}
					Object fieldValue = ReflectionUtils.getFieldValue(v, bean);
					Assert.isNotEmpty(String.valueOf(fieldValue), StringUtils.format("constant value is null, please check className:[{}], fieldName:[{}]", clazz.getName(), k));
				});
			}
		}
		Log.get().info("valid constant suc!");
	}
}
